/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * LoginFrame.java
 *
 * Created on 22-nov-2011, 20:32:09
 */
package edu.uoc.tdp.pac4.only5.gui.client;

import edu.uoc.tdp.pac4.only5.domain.EnumRole;
import edu.uoc.tdp.pac4.only5.domain.Rol;
import edu.uoc.tdp.pac4.only5.domain.User;
import edu.uoc.tdp.pac4.only5.exceptions.EespaisDatabaseException;
import edu.uoc.tdp.pac4.only5.manager.UserManager;
import edu.uoc.tdp.pac4.only5.exceptions.LoginException;
import edu.uoc.tdp.pac4.only5.tools.ResourceBundleTool;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.rmi.Naming;
import java.rmi.RemoteException;
import javax.swing.JComponent;
import javax.swing.JOptionPane;

/**
 *
 * @author Gerard
 */
public class LoginFrame extends javax.swing.JFrame implements ActionListener {

    private UserManager userManager;

    /** Creates new form LoginFrame */
    public LoginFrame() {
        initComponents();
        setTitle("eEspais - Only5");
        btn_login.addActionListener(this);
        try {
//            userManager = new UserManagerImpl(DataBaseConnectionManagerImpl.getInstance());
            userManager = (UserManager) Naming.lookup("rmi://localhost/UserManager");
        } catch (Exception ex) {
            showErrorMessageDialog(null, "error.generic.rmi");
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        txtPasswd = new javax.swing.JPasswordField();
        txtUser = new javax.swing.JTextField();
        btn_login = new javax.swing.JButton();
        lbl_user = new javax.swing.JLabel();
        lbl_password = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        btn_login.setText("Login");

        lbl_user.setText("User");

        lbl_password.setText("Password");

        jLabel2.setFont(new java.awt.Font("Marker Felt", 0, 75)); // NOI18N
        jLabel2.setText("eEspais");

        jLabel3.setFont(new java.awt.Font("Lucida Grande", 2, 13));
        jLabel3.setText("Simple spaces booking...");

        jLabel4.setFont(new java.awt.Font("Lucida Grande", 2, 13));
        jLabel4.setText("by Only5 software");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(97, 97, 97)
                .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(97, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addGap(129, 129, 129)
                .addComponent(btn_login)
                .addContainerGap(181, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lbl_user)
                    .addComponent(lbl_password))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 77, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txtPasswd, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtUser, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(87, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(254, Short.MAX_VALUE)
                .addComponent(jLabel4)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addGap(37, 37, 37)
                .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, 297, Short.MAX_VALUE)
                .addGap(33, 33, 33))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel3)
                .addGap(26, 26, 26)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbl_user)
                    .addComponent(txtUser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbl_password)
                    .addComponent(txtPasswd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btn_login)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 57, Short.MAX_VALUE)
                .addComponent(jLabel4)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(LoginFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(LoginFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(LoginFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(LoginFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */        
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new LoginFrame().setVisible(true);
            }
        });        
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btn_login;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel lbl_password;
    private javax.swing.JLabel lbl_user;
    private javax.swing.JPasswordField txtPasswd;
    private javax.swing.JTextField txtUser;
    // End of variables declaration//GEN-END:variables

    @Override
    public void actionPerformed(ActionEvent ae) {
        String value1 = txtUser.getText();
        StringBuilder passwd = new StringBuilder();
        passwd.append(txtPasswd.getPassword());
        try {
            validateUser(value1, passwd.toString());
            ClientNew page = new ClientNew();
            page.setVisible(true);
            this.setVisible(false);
        } catch (LoginException ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void validateUser(String userName, String password) throws LoginException {
        User user = null;
        try {
            user = userManager.getUserById(userName);
        } catch (RemoteException ex) {
            showErrorMessageDialog(null, "error.generic.rmi");
        } catch(EespaisDatabaseException ex){
            showErrorMessageDialog(null, "error.generic.databaseerror");
        } 
        if (user == null) {
            throw new LoginException("User not found!!!");
        }
        if (password.trim().equals(user.getPassword().trim())) {
            setRoleAndStoreToSession(user);
        } else {
            throw new LoginException("Incorrect Password!");
        }
    }

    private void setRoleAndStoreToSession(User user) {
        ClientSession.getInstance().setUser(user);
        Rol role;
        try {
            role = userManager.getRol(user.getRoleId());
            ClientSession.getInstance().setRole(EnumRole.valueOf(role.getRole_desc()));
        } catch (RemoteException ex) {
            showErrorMessageDialog(null, "error.generic.rmi");
        } catch(EespaisDatabaseException ex){
            showErrorMessageDialog(null, "error.generic.databaseerror");
        } 
    }
    
     private void showErrorMessageDialog(JComponent component, String key){
        JOptionPane.showMessageDialog(component, ResourceBundleTool.getInstance().getText(key), "Error", JOptionPane.ERROR_MESSAGE);
    }
}
